package com.jrx.anytxn.transaction.job.coupon.step;

import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.constant.CouponConstant;
import com.jrx.anytxn.customer.constant.CustomerConstant;
import com.jrx.anytxn.customer.dto.customer.CustomerRes;
import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.customer.service.ITlCouponDetailService;
import com.jrx.anytxn.number.exception.SegmentException;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.constant.Constant;
import com.jrx.anytxn.param.entity.PrCodeTable;
import com.jrx.anytxn.param.enums.RightsTypeEnum;
import com.jrx.anytxn.param.mapper.ext.ExtPrCodeTableMapper;
import com.jrx.anytxn.transaction.config.CouponConfig;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import com.jrx.anytxn.transaction.dto.common.SendSmsReq;
import com.jrx.anytxn.transaction.entity.AmLoanMainInfo;
import com.jrx.anytxn.transaction.job.coupon.dto.CustomerRightsDTO;
import com.jrx.anytxn.transaction.service.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * ClassName CouponMonthlyProcessor
 *
 * @author lujianyou
 * @version 1.0
 * @description 权益月活动 Processor
 * @date 2021/9/17 16:26
 **/
@Service
@Slf4j
public class CouponMonthlyProcessor implements ItemProcessor<AmLoanMainInfo, CustomerRightsDTO> {
    private static final String DEFAULT_CHANNEL = "channel01";
    private static final BigDecimal ONE_HUNDRED_NINETY_NINE = new BigDecimal("199");
    private static final BigDecimal FIVE_HUNDRED_NINETY_NINE = new BigDecimal("599");
    private static final BigDecimal NINE_HUNDRED_NINETY_NINE = new BigDecimal("999");

    @Autowired
    private CouponConfig couponConfig;
    @Autowired
    private ISegmentService segmentService;
    @Autowired
    private ITlCouponDetailService couponDetailService;
    @Autowired
    private ICustomerService customerService;
    @Autowired
    private ISmsService smsService;
    @Resource
    private ExtPrCodeTableMapper extPrCodeTableMapper;

    private static final Logger logger = LoggerFactory.getLogger(CouponMonthlyProcessor.class);


    @Override
    public CustomerRightsDTO process(AmLoanMainInfo item) throws Exception {

        log.info("权益月活动统计item:{}" , JSONObject.toJSONString(item));
        BigDecimal loanAmount = item.getLoanAmount();
        CouponConfig.Qualification qualification = couponConfig.getQualification();
        /**
         * 999 可兑换一个会员类月卡权益或出行类权益或购物类权益（三选一）
         * 599 可兑换一个会员类月卡权益或出行类权益（二选一）
         * 199 可兑换一个会员类月卡权益
         */
        String rightsQualificationId = null;
        String name = null;

        if(NINE_HUNDRED_NINETY_NINE.compareTo(loanAmount) <= 0){
           rightsQualificationId = qualification.getMemberId() + "," + qualification.getTripId() + "," + qualification.getShoppingId();
           name = "月消费满999元";
        }else if(FIVE_HUNDRED_NINETY_NINE.compareTo(loanAmount) <= 0){
            rightsQualificationId = qualification.getMemberId() + "," + qualification.getTripId();
            name = "月消费满599元";
        }else if(ONE_HUNDRED_NINETY_NINE.compareTo(loanAmount) <= 0){
            rightsQualificationId = qualification.getMemberId();
            name = "月消费满199元";
        }
        if(StringUtils.isNotBlank(rightsQualificationId)){
            Date today = new Date();
            String customerId = item.getCustomerId();
            // 判断当前活动是否已发
            List<TlCouponDetail> couponDetailList = couponDetailService.findByCustomerIdAndActivityIdWithPeriod(customerId,couponConfig.getActivity().getConsumptionFrom1To24ActivityId(),
                    "101",DateUtils.getMonthStartTime(today), DateUtils.getMonthEndTime(today));
            if(!couponDetailList.isEmpty()){
                log.info("客户id:{} 当月已发，不再发。",customerId);
                return null;
            }
            CustomerRightsDTO customerRightsDTO = new CustomerRightsDTO();
            CmCustomerRightInfo cmCustomerRightInfo = generateCustomerRightInfo(item,name,rightsQualificationId);
            TlCouponDetail tlCouponDetail = generateCouponDetail(item,cmCustomerRightInfo);
            customerRightsDTO.setCmCustomerRightInfo(cmCustomerRightInfo);
            customerRightsDTO.setTlCouponDetail(tlCouponDetail);
            log.info("客户id:{} 发券成功~",customerId);
            log.info("----组装发送短信的参数----");
            SendSmsReq req = new SendSmsReq();
            String tenantId = cmCustomerRightInfo.getTenantId();
            req.setCustomerId(cmCustomerRightInfo.getCustomerId());
            req.setChannel(cmCustomerRightInfo.getChannel());
            req.setTenantId(tenantId);
            req.setMobile(tlCouponDetail.getMobile());
            String currentTimeMillis = System.currentTimeMillis() + "";
            String seqNo = (int)(Math.random() * 100000) + currentTimeMillis;
            req.setSeqNo(seqNo);
            req.setSmsType(CouponConstant.SMS_TYPE_RIGHTS_REMINDER);
            req.setLoanId(name+"的兑换权益资格");
            req.setExpireDate(getLimitTime(tenantId));
            smsService.sendSmsMq(req);
            return customerRightsDTO;
        }
        return null;
    }

    /**
     * 获取活动时间
     * @return
     */
    private String getLimitTime(String tenantId) {
        // 默认值为每月25号10点30分
        Integer limitDay = 25;
        int limitHour = 10;
        int limitMinute = 30;
        try {
            PrCodeTable prCodeTable = extPrCodeTableMapper.selectByTypeIdAndCodeId("EXCHANGE_TIME", "exchangeTime", tenantId);
            if (Objects.nonNull(prCodeTable)) {
                String[] periods = prCodeTable.getCodeName().split("-");
                if (periods.length == 3) {
                    // 每月几号
                    limitDay = Integer.valueOf(periods[0]);
                    // 几点
                    limitHour = Integer.parseInt(periods[1]);
                    // 几分
                    limitMinute = Integer.parseInt(periods[2]);
                }
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
            logger.warn("解析权益兑换的日-时-分段出错：{}", e);
        }
        return limitDay + "号" + limitHour + ":" + (limitMinute < 10 ? "0" + limitMinute : limitMinute);
    }

    private TlCouponDetail generateCouponDetail(AmLoanMainInfo item,CmCustomerRightInfo customerRightInfo) throws TxnBizException {
        TlCouponDetail tlCouponDetail = new TlCouponDetail();
        String customerId = item.getCustomerId();
        try {
            tlCouponDetail.setId(segmentService.getId(CustomerConstant.TL_COUPON_DETAIL_INFO));
        } catch (SegmentException segmentException) {
            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
        }
        tlCouponDetail.setTenantId("101");
        tlCouponDetail.setOrganizationId(TransBizConstant.DEFAULT_ORG_ID);
        tlCouponDetail.setChannel(DEFAULT_CHANNEL);
        tlCouponDetail.setCustomerId(customerId);

        tlCouponDetail.setRightsId(customerRightInfo.getRightsQualificationId());
        tlCouponDetail.setRightsName(customerRightInfo.getRightsName());
        tlCouponDetail.setRightsType(customerRightInfo.getRightsType());
        tlCouponDetail.setCustomerRightsId(customerRightInfo.getId());
        tlCouponDetail.setCouponSummaryId(0L);

        CustomerRes customerRes = customerService.getCustomerByChannelAndCustomerIdAndTensnId(DEFAULT_CHANNEL,customerId,"101");
        tlCouponDetail.setChineseName(customerRes.getFirstLevel().getChineseName());
        tlCouponDetail.setIdNumber(customerRes.getFirstLevel().getIdNumber());
        tlCouponDetail.setMobile(customerRes.getSecondLevel().getMobile());

        Date now = new Date();
        tlCouponDetail.setCreateTime(now);
        tlCouponDetail.setUpdateTime(now);
        tlCouponDetail.setUpdateBy(customerId);
        tlCouponDetail.setRecordVersionNumber(Constant.VERSION_NUMBER);
        tlCouponDetail.setActivityId(customerRightInfo.getActivityId());

        return tlCouponDetail;
    }

    private CmCustomerRightInfo generateCustomerRightInfo(AmLoanMainInfo item,String rightsName,String qualificationId) throws TxnBizException {
        CmCustomerRightInfo customerRightInfo = new CmCustomerRightInfo();

        try {
            customerRightInfo.setId(segmentService.getId(CustomerConstant.CM_CUSTOMER_RIGHT_INFO));
        } catch (SegmentException segmentException) {
            throw new TxnBizException(TxnRespCode.GET_SEGMENT_ID_ERROR);
        }
        customerRightInfo.setTenantId("101");
        customerRightInfo.setChannel(DEFAULT_CHANNEL);
        customerRightInfo.setCustomerId(item.getCustomerId());
        customerRightInfo.setOrganizationId("0001");
        customerRightInfo.setEffectDate(DateUtils.getThisMonthDate(new Date(),25));
        customerRightInfo.setExpiresDate(DateUtils.getMonthEndTime(new Date()));
        customerRightInfo.setRightsType(RightsTypeEnum.QUALIFICATION.getCode());
        customerRightInfo.setRightsName(rightsName);

        customerRightInfo.setLoanId("");
        customerRightInfo.setAllowProducts("XIBXAH000001");
        customerRightInfo.setRightsStatus(CustomerConstant.RIGHTS_STATUS_0);

        Date now = new Date();
        customerRightInfo.setCreateTime(now);
        customerRightInfo.setUpdateTime(now);
        customerRightInfo.setUpdateBy(item.getCustomerId());
        customerRightInfo.setRecordVersionNumber(Constant.VERSION_NUMBER);
        customerRightInfo.setActivityId(couponConfig.getActivity().getConsumptionFrom1To24ActivityId());
        customerRightInfo.setCouponCate("");
        customerRightInfo.setRightsQuantity(1);
        customerRightInfo.setRightsQualificationId(qualificationId);
        customerRightInfo.setProductCode("XIBXAH000001");
        customerRightInfo.setCycleUse(CouponConstant.CYCLE_USE_N);

        return customerRightInfo;
    }

}
